import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useTranslation } from 'react-i18next';
import {
  Container,
  Typography,
  Box,
  Paper,
  Button,
  TextField,
  Grid,
  Avatar,
  LinearProgress
} from '@mui/material';
import { RootState } from '../redux/store';
import { AppDispatch } from '../redux/store';
import { updateProfile } from '../redux/slices/authSlice';
import { addAlert } from '../redux/slices/uiSlice';

const Profile = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { user, loading } = useSelector((state: RootState) => state.auth);
  const { t } = useTranslation();
  
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    bio: ''
  });
  
  const [isEditing, setIsEditing] = useState(false);
  
  useEffect(() => {
    if (user) {
      setFormData({
        firstName: user.firstName || '',
        lastName: user.lastName || '',
        bio: user.bio || ''
      });
    }
  }, [user]);
  
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };
  
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    
    try {
      await dispatch(updateProfile(formData));
      dispatch(addAlert({
        type: 'success',
        message: t('profile.success.updated')
      }));
      setIsEditing(false);
    } catch (error) {
      dispatch(addAlert({
        type: 'error',
        message: t('profile.errors.updateFailed')
      }));
    }
  };
  
  if (loading || !user) {
    return <LinearProgress />;
  }
  
  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Typography variant="h4" gutterBottom>
        {t('profile.title')}
      </Typography>
      
      <Paper sx={{ p: 3, mb: 3 }}>
        <Box display="flex" alignItems="center" mb={3}>
          <Avatar
            sx={{ width: 80, height: 80, mr: 2 }}
            src={user.profilePicture}
          >
            {user.username?.charAt(0).toUpperCase()}
          </Avatar>
          <Box>
            <Typography variant="h5">{user.username}</Typography>
            <Typography variant="body1" color="textSecondary">
              {user.email}
            </Typography>
          </Box>
        </Box>
        
        {isEditing ? (
          <form onSubmit={handleSubmit}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label={t('profile.firstName')}
                  name="firstName"
                  value={formData.firstName}
                  onChange={handleChange}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label={t('profile.lastName')}
                  name="lastName"
                  value={formData.lastName}
                  onChange={handleChange}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  multiline
                  rows={4}
                  label={t('profile.bio')}
                  name="bio"
                  value={formData.bio}
                  onChange={handleChange}
                />
              </Grid>
              <Grid item xs={12}>
                <Button
                  type="submit"
                  variant="contained"
                  color="primary"
                  sx={{ mr: 2 }}
                >
                  {t('common.save')}
                </Button>
                <Button
                  variant="outlined"
                  onClick={() => setIsEditing(false)}
                >
                  {t('common.cancel')}
                </Button>
              </Grid>
            </Grid>
          </form>
        ) : (
          <>
            <Typography variant="h6" gutterBottom>
              {t('profile.personalInfo')}
            </Typography>
            <Typography variant="body1">
              <strong>{t('profile.firstName')}:</strong> {user.firstName || t('profile.notProvided')}
            </Typography>
            <Typography variant="body1">
              <strong>{t('profile.lastName')}:</strong> {user.lastName || t('profile.notProvided')}
            </Typography>
            <Typography variant="body1" paragraph>
              <strong>{t('profile.bio')}:</strong> {user.bio || t('profile.noBio')}
            </Typography>
            
            <Button
              variant="contained"
              color="primary"
              onClick={() => setIsEditing(true)}
            >
              {t('profile.editProfile')}
            </Button>
          </>
        )}
      </Paper>
      
      <Paper sx={{ p: 3 }}>
        <Typography variant="h6" gutterBottom>
          {t('profile.accountSettings')}
        </Typography>
        <Typography variant="body1">
          <strong>{t('profile.currentLevel')}:</strong> {t(`challenge.levels.${user.progress?.currentLevel}`) || t('challenge.levels.beginner')}
        </Typography>
        <Typography variant="body1">
          <strong>{t('profile.theme')}:</strong> {t(`settings.${user.preferences?.theme}`) || t('settings.light')}
        </Typography>
        <Typography variant="body1">
          <strong>{t('profile.aiProvider')}:</strong> {user.preferences?.aiProvider || 'Default'}
        </Typography>
      </Paper>
    </Container>
  );
};

export default Profile; 